require("apm_core")
require("extension")

local G_DEBUG = true

if G_DEBUG == false then
    function logDebug(fmt,...) end
    function logInfo(fmt,...) end
    function logWarn(fmt,...) end
    function logError(fmt,...) end
    function logFatal(fmt,...) end
end

--[[
local function decodeURI()
	local char, gsub, tonumber = string.char, string.gsub, tonumber
	local function _(hex) return char(tonumber(hex, 16)) end
	function
end
]]
local hex = {}
for i=0,255 do
	hex[string.format("%0x", i)] = string.char(i)
	hex[string.format("%0X", i)] = string.char(i)
end
local function decodeURI(s)
	return (s:gsub('%%(%x%x)', hex))
end

function post_analysis()
	local ApmData = require("ApmData")
	if ApmData.getL7Proto() ~= 80 then return end
--	if ApmData.getMsgType() ~= 1 then return end
	
	local s_title = ApmData.getField("transaction.title", 1)
	if s_title ~= nil then
		s_title = decodeURI(s_title)
		ApmData.replaceField("transaction.title", s_title)
		if not string.endswith(s_title, ".png") then
			if s_title == "http://nm.czbank.com:80/channel_s/run" then
				logInfo("title:[%s]", "channel_s/run")
			elseif string.startswith(s_title, "http://nm.czbank.com:80/ebank/") or string.startswith(s_title, "http://nm.czbank.com/ebank/") then
				local _, _, value = string.find(s_title, "/([a-zA-Z0-9_%.]-)$")
				if value ~= nil then
					logInfo("title 2:[%s]", value)
				else
					logInfo("title 2:[%s]", s_title)
				end
			elseif s_title == "http://localhost/f5.html" then
				logInfo("title 3:[%s]", "f5.html")
			elseif string.startswith(s_title, "http://nm.czbank.com:80/user/") then
				local _, _, value = string.find(s_title, "/(user/.*)$")
				if value ~= nil then
					logInfo("title 4:[%s]", value)
				else
					logInfo("title 4:[%s]", s_title)
				end
			else
				logInfo("title 5:[%s]", s_title)
			end
		end
	end
	
	local s_req = ApmData.getField("request.http.body.1", 1)
	if s_req ~= nil then
		--logInfo("REQ:[%s]", s_req)
	end
	
	local s_resp = ApmData.getField("response.http.body.1", 1)
	if s_resp ~= nil then
		--logInfo("RESP:[%s]", s_resp)
	end
	
	return
end
